import re, os, sys, json, chardet, datetime
from fastapi import FastAPI
from yaml import load, dump
import hashlib
import threading
import uuid

try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

sys.path.append(os.getcwd())

green = "\033[1;32m"
red = "\033[1;31m"
white = "\033[1;37m"

def error_helper(e, doc_url=''):
    error_print(e)
    error_print("查看：", doc_url)

def error_print(*s):
    print(red, end="")
    print(*s)
    print(white, end="")

def success_print(*s):
    print(green, end="")
    print(*s)
    print(white, end="")

class dotdict(dict):
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__
def object_hook(dict1):
    for key, value in dict1.items():
        if isinstance(value, dict):
            dict1[key] = dotdict(value)
        else:
            dict1[key] = value
    return dotdict(dict1)

try:
    stream = open('./config.yml', encoding='utf8')
except:
    error_print('加载配置失败')
    stream = open('example.config.yml', encoding='utf8')


settings = load(stream, Loader=Loader)
settings = dotdict(settings)
settings_str_toprint = dump(dict(settings))
settings_str_toprint = re.sub(r':', ":"+"\033[1;32m", settings_str_toprint)
settings_str_toprint = re.sub(r'\n', "\n\033[1;31m", settings_str_toprint)
print("\033[1;31m", end="")
print("加载配置\n", end="")
print(settings_str_toprint, end="")
print("\033[1;37m")

settings_str = json.dumps(settings)
settings = json.loads(settings_str, object_hook=object_hook)

#请求成功返回信息
def response_success(data):
    return {'code': 10000,'data':data}

#请求失败返回的信息
def response_fail(massage:str='', code:int=40001):
    return {'massage':massage, 'code':code}

#生成一个uuid
def get_uuid():
    get_timestamp_uuid = uuid.uuid4()  # 根据 时间戳生成 uuid , 保证全球唯一
    return str(get_timestamp_uuid)

#返回当前时间
def now_date():
    current_time = datetime.datetime.now()
    return current_time.strftime('%Y-%m-%d %H:%M:%S')

#字符串md5处理
def md5(string):
    md5_hash = hashlib.md5()
    md5_hash.update(string.encode("utf-8"))
    return md5_hash.hexdigest()

#获得文件内容
def read_file(file_path):
    with open(file_path, 'rb') as f:
        b = f.read()
        result = chardet.detect(b)
    with open(file_path, 'r', encoding=result['encoding']) as file:
        content = file.read()
    return content

#写文件内容
def write_file(file_path, content):
    dir_path = os.path.dirname(file_path)
    os.makedirs(dir_path, exist_ok=True)
    with open(file_path, 'w', encoding='utf8') as file:
        file.write(content)

#获得目录下的所有文件列表
def dir_file(path):
    source_folder_path = os.path.join(os.getcwd(), path)
    all_files = []
    for root, dirs, files in os.walk(source_folder_path):
        for file in files:
            all_files.append([root, file])

    if len(all_files) == 0:
        return []
    
    return all_files

#获得文本第一行文本
def get_first_line(file_path):
    with open(file_path, 'rb') as f:
        b = f.read()
        result = chardet.detect(b)
    with open(file_path, 'r', encoding=result['encoding']) as file:
        first_line = file.readline()
    return first_line


#是否为json代码的字符串
def is_json(response: str) -> bool:
    try:
        json.loads(response)
        return True
    except ValueError as e:
        return False

class CounterLock:
    def __init__(self):
        self.lock = threading.Lock()
        self.waiting_threads = 0
        self.waiting_threads_lock = threading.Lock()

    def acquire(self):
        with self.waiting_threads_lock:
            self.waiting_threads += 1
        acquired = self.lock.acquire()

    def release(self):
        self.lock.release()
        with self.waiting_threads_lock:
            self.waiting_threads -= 1

    def get_waiting_threads(self):
        with self.waiting_threads_lock:
            return self.waiting_threads

    def __enter__(self):  # 实现 __enter__() 方法，用于在 with 语句的开始获取锁
        self.acquire()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):  # 实现 __exit__() 方法，用于在 with 语句的结束释放锁
        self.release()
        
app = FastAPI(title="任务型ai对话机器人",
              description="任务型ai对话机器人 API",
              version="1.0.1",
              openapi_url="/docs/openapi.json",
              docs_url = "/docs",
              redoc_url=None)